package cn.touna.jss.modules.third.baiqishi.service.impl;

import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.modules.third.baiqishi.entity.IpAttribution;
import cn.touna.jss.modules.third.baiqishi.entity.IpAttributionExample;
import cn.touna.jss.modules.third.baiqishi.mapper.IpAttributionMapper;
import cn.touna.jss.modules.third.baiqishi.service.BaiqishiDbService;
import cn.touna.risk.api.exception.ServiceException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 ********************************************************
 * 白骑士数据库操作接口实现
 * @author zhangjialian
 * @Date 2018-08-24 17:48
 * @Version V1.0
 ********************************************************/
@Service
public class BaiqishiDbServiceImpl implements BaiqishiDbService {
    @Autowired
    private IpAttributionMapper ipAttributionMapper;
    @Override
    public Integer saveIpAttribution(IpAttribution record) {
        if(null==record) {return 0;}
        IpAttribution ipData=queryIpAttribution(record.getIp());
        if(ipData==null){
            //查询IP对应归属地数据未入库，进行入库
            ipAttributionMapper.insert(record);
        }
        return 0;
    }

    @Override
    public IpAttribution queryIpAttribution(String ip) {
        if(StringUtils.isEmpty(ip)){
            throw new ServiceException(SystemErrorCodeEnum.JSS_PARAM_CHECK_FAILED.getErrorCode(),
                "请求查询ip不能为空");
        }
        IpAttributionExample example=new IpAttributionExample();
        IpAttributionExample.Criteria criteria=example.createCriteria();
        criteria.andIpEqualTo(ip);
        List<IpAttribution> list= ipAttributionMapper.selectByExample(example);
        return (list!=null && list.size()>0)?list.get(0):null;
    }
}
